package com.example.shopping_web_back.controller;

import com.example.shopping_web_back.pojo.GoodsImages;
import com.example.shopping_web_back.pojo.Result;
import com.example.shopping_web_back.service.GoodsImagesService;
import com.example.shopping_web_back.utils.ThreadLocalUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@Validated
@RequestMapping("/GoodsImages")
public class GoodsImagesController {

    @Autowired
    private GoodsImagesService goodsImagesService;

    private static final String CURRENT_PATH = System.getProperty("user.dir");
    private static final String IMAGE_DIR = CURRENT_PATH + "/uploads/image/goods/goodsImage/";

    @PostMapping("/getGoodsImage")
    public Result<List<GoodsImages>> getGoodsImages(@RequestParam("ID") Integer id) {
        List<GoodsImages> goodsImagesList = goodsImagesService.getGoodsImages(id);
        return Result.success(goodsImagesList);
    }

    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file")MultipartFile Image) throws IOException {
        Map<String, Object> map = ThreadLocalUtil.get();
        String businessName = (String) map.get("Business_name");
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String originalFileName = Image.getOriginalFilename();
        String fileExtension = "";
        if(originalFileName != null && originalFileName.lastIndexOf('.') > 0) {
            fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        }
        File dir = new File(IMAGE_DIR);
        String fileName = businessName + "_" +timestamp + fileExtension;
        Path filePath = Paths.get(IMAGE_DIR + fileName);
        Files.copy(Image.getInputStream(), filePath);
        return Result.success("http://8.138.173.30:8080/image/goods/goodsImage/" + fileName);
    }

    @Data
    public static class GoodsImage {
        private List<String> goodsImage;
    }

    public void renameFile(String oldFileName, String newFileName) throws IOException {
        File dir = new File(IMAGE_DIR);
        File fileToReName = new File(dir, oldFileName);
        if(fileToReName.exists()) {
            File renameFile = new File(dir, newFileName);
            boolean success = fileToReName.renameTo(renameFile);
            if(!success) {
                throw new IOException("Failed to rename file to " + newFileName);
            }
        }
    }

    @PostMapping("/add")
    public Result addGoodsImages(@RequestBody GoodsImage goodsImages, @RequestParam("ID") Integer id) throws IOException {
        List<String> goodsImageUrl = goodsImages.getGoodsImage();
        for(int i = 1; i < goodsImageUrl.size(); i++)
        {
            String fileName = goodsImageUrl.get(i).substring(goodsImageUrl.get(i).lastIndexOf('/') + 1);
            String newFileName = fileName.substring(0, fileName.lastIndexOf('.')) + "_" + id + "_" + i + fileName.substring(fileName.lastIndexOf('.'));
            renameFile(fileName, newFileName);
            goodsImagesService.addGoodsImages(id, "http://8.138.173.30:8080/image/goods/goodsImage/" + newFileName);
        }
        return Result.success();
    }

    @PostMapping("/delete")
    public Result deleteGoodsImages(@RequestParam String goodsImages) throws IOException {
        String fileName = goodsImages.substring(goodsImages.lastIndexOf('/') + 1);
        File dir = new File(IMAGE_DIR);
        File fileToDelete = new File(dir, fileName);
        Files.delete(fileToDelete.toPath());
        goodsImagesService.deleteGoodsImages(goodsImages);
        return Result.success();
    }

    @PostMapping("/deleteAll")
    public Result deleteGoodsImage(@RequestParam Integer id) throws IOException {
        List<GoodsImages> listToDelete = goodsImagesService.getGoodsImages(id);
        File dir = new File(IMAGE_DIR);
        for (GoodsImages goodsImages : listToDelete) {
            File file = new File(dir, goodsImages.getGoodsImage().substring(goodsImages.getGoodsImage().lastIndexOf('/')));
            Files.delete(file.toPath());
            goodsImagesService.deleteGoodsImages(goodsImages.getGoodsImage());
        }
        return Result.success();
    }

    @PostMapping("/change")
    public Result changeGoodsImages(@RequestBody GoodsImage goodsImage, @RequestParam("ID") Integer id) throws IOException {
        List<String> goodsImageUrl = goodsImage.getGoodsImage();
        GoodsImages oldGoodsImage = new GoodsImages(), newGoodsImage = new GoodsImages();
        oldGoodsImage.setGoodsId(id);
        newGoodsImage.setGoodsId(id);
        for(int i = 0; i < goodsImageUrl.size(); i++)
        {
            String fileNameInteger = goodsImageUrl.get(i).substring(goodsImageUrl.get(i).lastIndexOf('_') + 1, goodsImageUrl.get(i).lastIndexOf('.'));
            String fileName = goodsImageUrl.get(i).substring(goodsImageUrl.get(i).lastIndexOf('/') + 1);
            if(fileNameInteger.length() == 1)
            {
                if(Integer.parseInt(fileNameInteger) != i) {
                    String newFileName = fileName.substring(0, fileName.lastIndexOf('_')) + "_" + i + fileName.substring(fileName.lastIndexOf('.'));
                    renameFile(fileName, newFileName);
                    oldGoodsImage.setGoodsImage(goodsImageUrl.get(i));
                    newGoodsImage.setGoodsImage("http://8.138.173.30:8080/image/goods/goodsImage/" + newFileName);
                    goodsImagesService.changeGoodsImages(oldGoodsImage, newGoodsImage);
                }
            }else {
                String newFileName = fileName.substring(0, fileName.lastIndexOf('.')) + "_" + id + "_" + i + fileName.substring(fileName.lastIndexOf('.'));
                renameFile(fileName, newFileName);
                goodsImagesService.addGoodsImages(id, "http://8.138.173.30:8080/image/goods/goodsImage/" + newFileName);
            }
        }
        return Result.success();
    }
}
